" Inspired by http://jeetworks.org/node/146
function! <SID>SendCurrentRangeAsMarkedUpPythonToMaya() range
    "" get lines
    let [lnum1, col1] = getpos("'<")[1:2]
    let [lnum2, col2] = getpos("'>")[1:2]
    let lines = getline(lnum1, lnum2)

    " Trying to send the string to Python over the command line has probably
    " been one of the worst experiences of my life as a programmer. It just
    " doesn't work. Write to a temp file instead and read it from within Maya.

    " Open new buffer
    new
    " Paste. For some stupid reason we have to read the return value
    let x = append(0, lines)
    " Delete empty lines
    s,\n^$,,g
    " Write to temp file
    write! $MAYA_SCRIPT_PATH_BASE/MELVIM/lala.txt
    " Close the buffer (buffer wipe)
    bwipeout
    execute "silent !python \"\\%MAYA_SCRIPT_PATH_BASE\\%\\MELVIM\\sendToMaya.py\" ndhEvalMELVIM;" 
endfunction

function! BindF2()
  nnoremap <buffer> <F2> lBye<C-w><C-q>e
endfunction
    
command! -bang -range SendToMaya :call s:SendCurrentRangeAsMarkedUpPythonToMaya()

" Split window horizontally, load history in bottom window
command! ShowHistorySplit normal <C-w><C-o><C-w><C-s><C-w><C-w>:e $MAYA_SCRIPT_PATH_BASE/history.mel<CR><C-w><C-w>
command! SwitchToCommandHelpSplit normal <C-w><C-o><C-w><C-s><C-w><C-w>:e $MAYA_SCRIPT_PATH_BASE/cmdHelp.melhelp<CR>/Synopsis: <C-r>z\><CR>/-<CR>n

""""""""""""
" Bindings "
""""""""""""

" Send selected text to Maya, display the result in a split window.
vmap <Enter> :SendToMaya<CR>:ShowHistorySplit<CR>

" source <current file>
" Apparently it's not possible to get this stupid tool chain to escape backslashes, use forward slashes instead.
nmap ,s :execute "silent !python \"\\%MAYA_SCRIPT_PATH_BASE\\%\\MELVIM\\sendToMaya.py\" " . ("source \\\"" . substitute(expand("%:p"), "\\", "/", "g") . "\\\";")<CR><CR>

" Save, then source.
nmap ,w :w<CR>,s

" Switch to help for the command under cursor in a split window. Move to a
" command argument, then press F2 again to yank the argument and close the
" help window.
nmap <F2> lb"zye:SwitchToCommandHelpSplit<CR>:call BindF2()<CR>

imap .. +".")<Esc>bbhi(<Esc>wwlla
